import { message } from 'antd'
import axios from 'axios'
import { getToken, hasToken } from './storage'
import history from './history'
import { removeToken } from '@/utils/storage'
const _axios = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/'
})

// 请求拦截器
_axios.interceptors.request.use(
  function (config) {
    const token = getToken()
    if (hasToken()) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
_axios.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    if (!error.response) {
      message.error('网络错误')
      return Promise.reject(error)
    }
    if (error.response.status === 401) {
      message.error('登录超时,请重新登录')
      removeToken()
      history.push('/login', { from: history.location.pathname })
      return Promise.reject(error)
    }
    return Promise.reject(error)
  }
)

export default _axios
